package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.DrivingService;
import com.gljx.web.service.OwnCarTrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class OwnCarTrainController {

	//自动注入
	@Autowired
	private OwnCarTrainService ownCarTrainService;
	
	//自动注入
	@Autowired
	private DrivingService drivingService;
		
	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;
	
	/**
	 * 查询考前模拟收费
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryOwnCarTrain/look.action")
	public String queryOwnCarTrain(HttpServletRequest request,String type){
		PageBean<OwnCarTrain> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<OwnCarTrain> ownCarTrains = pb.getBeanList();
			for (OwnCarTrain ownCarTrain : ownCarTrains) {
				//查询子类信息
				List<OwnCarTrainEntry> otherRefundBillEntrys = ownCarTrainService.selectOwnCarTrainEntry(ownCarTrain.getFid(), "", "");
				//放入集合中
				ownCarTrain.setOwnCarTrainEntrys(otherRefundBillEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("pb", pb);
			request.setAttribute("ownCarTrains", ownCarTrains);
			request.setAttribute("flag", type);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/financialManagement/ownCarTrain/ownCarTrainList";
	}
	
	/**
	 * 根据条件查询考前模拟收费
	 * @param request
	 * @param cfchepai 姓名
	 * @param drivingName 驾校名称
	 * @param beginTime 业务开始时间
	 * @param endTime 业务结束时间
	 * @return
	 */
	@RequestMapping("/queryOwnCarTrainByInfo")
	public String queryOwnCarTrainByInfo(HttpServletRequest request,String cfchepai,String drivingName,String chergetype,String beginTime,String endTime){
		PageBean<OwnCarTrain> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
			cfchepai = cfchepai.trim();
			drivingName = drivingName.trim();
			//获取分页
			pb = getPageBean2(request,user.getFcompanyid(),cfchepai,drivingName,chergetype,beginTime,endTime);
			//获取分页数据
			List<OwnCarTrain> ownCarTrains = pb.getBeanList();
			for (OwnCarTrain ownCarTrain : ownCarTrains) {
				//查询子类信息
				List<OwnCarTrainEntry> otherRefundBillEntrys = ownCarTrainService.selectOwnCarTrainEntry(ownCarTrain.getFid(), cfchepai, drivingName);
				//放入集合中
				ownCarTrain.setOwnCarTrainEntrys(otherRefundBillEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("chergetype", chergetype);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("cfchepai", cfchepai);
			request.setAttribute("drivingName", drivingName);
			request.setAttribute("pb", pb);
			request.setAttribute("ownCarTrains", ownCarTrains);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/financialManagement/ownCarTrain/ownCarTrainList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @param type 
	 * @return
	 */
	@RequestMapping("/insertOwnCarTrain")
	public String insertOwnCarTrain(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
        //查询所有协议驾校
        List<Driving> drivings = drivingService.queryDrivingAll(user.getFcompanyid());
        //获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_owncartrain",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("KQMN");
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//开始时间
		String time = sdf.format(new Date());
		//把数据传到页面
		request.setAttribute("time", time);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("drivings", drivings);
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		return "/backHome/financialManagement/ownCarTrain/editOwnCarTrain";
	}
	
	/**
	 * 
	 * @param request
	 * @param ownCarTrain 父类对象
	 * @param fid 判断添加，修改
	 * @return
	 */
	@RequestMapping("/editOwnCarTrain")
	public String editOwnCarTrain(HttpServletRequest request,OwnCarTrain ownCarTrain,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		ownCarTrain.setFcontrolunitid(user.getFcompanyid());
		//公司id
		ownCarTrain.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		ownCarTrain.setFhandlerid(user.getFid());
		//**获取子类信息集合**//*
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//姓名
		String[] cfchepai = request.getParameterValues("cfchepai");
		//次数
		String[] cfchexing = request.getParameterValues("cfchexing");
		//科目
		String[] cfkemu = request.getParameterValues("cfkemu");
		//车型
		String[] cfcartype = request.getParameterValues("cfcartype");
		//协议驾校id
		String[] cfxyjsid = request.getParameterValues("cfxyjsid");
		//单价
		String[] cfprice = request.getParameterValues("cfprice");
		//金额
		String[] cfamount = request.getParameterValues("cfamount");
		//协议驾校名称
		//String[] drivingName = request.getParameterValues("drivingName");
		//人数
		String[] cfqty = request.getParameterValues("cfqty");
		//摘要
		String[] cfdesc = request.getParameterValues("cfdesc");
		//车牌号码   rhc
        String [] cfcarnumber=request.getParameterValues("cfcarnumber");
		//添加或修改
		ownCarTrainService.editOwnCarTrain(ownCarTrain,fseq,cfchepai,cfchexing,cfkemu,cfcartype,cfxyjsid,cfprice,cfamount,cfqty,cfdesc,cfcarnumber,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
            customLogService.addLog("财务管理", "对考前模拟收费进行添加操作", null, user.getFid());
            //重定向到添加页面
			return "redirect:/DrivingSys/insertOwnCarTrain?type=3";
		}else{
			//添加日志
            customLogService.addLog("财务管理", "对考前模拟收费进行修改操作", null, user.getFid());
            //重定向到查询页面
			return "redirect:/DrivingSys/queryOwnCarTrain/look.action?type=4";
		}
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryownCarTrainByFid")
	public String queryownCarTrainByFid(HttpServletRequest request,String fid){
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //查询父类信息
		OwnCarTrain ownCarTrain = ownCarTrainService.queryOwnCarTrainByFid(fid);
        //查询所有协议驾校
        List<Driving> drivings = drivingService.queryDrivingAll(user.getFcompanyid());
        //查询子类信息
		List<OwnCarTrainEntry> ownCarTrainEntrys = ownCarTrainService.selectOwnCarTrainEntry(fid, "", "");
		//查询所有的车型
		List<String> carTypes = customLogService.queryCarTypeAll();
        //查询是否是经办人
        Axamine axamine = new Axamine();
        boolean state = axamine.selectAuditPerson(ownCarTrain.getFnumber());
        //把数据传到页面
        request.setAttribute("AuditState", state);
        request.setAttribute("carTypes", carTypes);
		request.setAttribute("drivings", drivings);
		request.setAttribute("ownCarTrain", ownCarTrain);
		request.setAttribute("ownCarTrainEntrys", ownCarTrainEntrys);
        request.setAttribute("key", ActivitiKey.PUBLIC_KEY);
        return "/backHome/financialManagement/ownCarTrain/editOwnCarTrain";
	}
	
	/**
	 * 根据fid删除
	 * @param request
	 * @param deleteId 多个
	 * @param fid 单个
	 * @return
	 */
	@RequestMapping("/deleteOwnCarTrainByFid")
    public String deleteOwnCarTrainByFid(HttpServletRequest request, String[] deleteId, String fid, String[] fnumber, String fnumber2) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
        ownCarTrainService.deleteOwnCarTrainByFid(deleteId, fid, fnumber, fnumber2);
        //添加日志
        customLogService.addLog("财务管理", "对考前模拟收费进行删除操作", null, user.getFid());
        //重定向到查询页面
		return "redirect:/DrivingSys/queryOwnCarTrain/look.action";
	}
	
	/**
	 * 审核，反审核
	 * @param request
	 * @param type 1：审核，2：反审核
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditOwnCarTrain")
	@ResponseBody
	public int auditOwnCarTrain(HttpServletRequest request, String type, String fid, String message, String state, String fnumber) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//审核，反审核
		int i = ownCarTrainService.auditOwnCarTrain(fid, type, user.getFid(), message, state, fnumber);
        String ms;
        if ("1".equals(type)) {
            ms = "审核";
        } else {
            ms = "反审核";
        }
        //添加日志
        customLogService.addLog("财务管理", "对考前模拟收费进行" + ms + "操作单据编号 " + fnumber, null, user.getFid());
        return i;
	}

    /**
     * 提交
     * @param fid
     * @return
     */
    @RequestMapping("/submitOwnCarTrain")
    @ResponseBody
    public int submitOwnCarTrain(String fid, HttpServletRequest request, String fnumber, String auditState) {
        OwnCarTrain ownCarTrain = new OwnCarTrain();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        ownCarTrain.setFid(fid);
        ownCarTrain.setFlastupdateuserid(user.getFid());
        ownCarTrain.setCfbillstate(4L);
		//创建流程
		Axamine axamine = new Axamine();
        axamine.submissionProcess(fnumber);
        int i = ownCarTrainService.modifyOwnCarTrain(ownCarTrain);
        //添加日志
        customLogService.addLog("财务管理", "对考前模拟收费进行提交操作单据编号 " + fnumber, null, user.getFid());
        return i;
    }

    @SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<OwnCarTrain> getPageBean2(HttpServletRequest request,String companyId,String cfchepai,String drivingName,String chergetype,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate,t.cfdycs,t.chargetype ");
		psql.append(" from ct_ds_owncartrain t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid");
		psql.append(" left join ct_ds_owncartrainentry o on t.fid = o.fparentid left join ct_ds_driving d on o.cfxyjsid = d.fid ");
		psql.append(" where t.fcontrolunitid = '"+companyId+"'");
		if("".equals(cfchepai)){
			
		}else{
			psql.append(" and o.cfchepai like '%"+cfchepai+"%'");
		}
		if("".equals(drivingName)){
			
		}else{
			psql.append("  and d.fname_l2 like '%"+drivingName+"%'");
		}
		if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 100; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= ownCarTrainService.selectPage(pindex, psql.toString(), psize);
		PageBean<OwnCarTrain> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<OwnCarTrain>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<OwnCarTrain> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate,t.cfdycs,t.chargetype from ");
		psql.append(" ct_ds_owncartrain t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 10; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= ownCarTrainService.selectPage(pindex, psql.toString(), psize);
		PageBean<OwnCarTrain> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<OwnCarTrain>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=ownCarTrainService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param response
     * @param request
     * @param cfchepai
     * @param drivingName
     * @param chergetype
     * @param beginTime
     * @param endTime
     */
    @RequestMapping("/importOwnCarTrain")
    public void importOwnCarTrain(HttpServletResponse response, HttpServletRequest request, String cfchepai, String drivingName, String chergetype, String beginTime, String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<OwnCarTrainEntry> ownCarTrainEntrys = ownCarTrainService.selectOwnCarTrainByInfo(user.getFcompanyid(), cfchepai.trim(), drivingName.trim(), chergetype, beginTime, endTime);
        for (OwnCarTrainEntry ownCarTrainEntry : ownCarTrainEntrys) {
            data.add(ownCarTrainEntry.getFnumber());//单据编码
            data.add(ownCarTrainEntry.getFbizdate());//业务日期(缴费日期)
            data.add(ownCarTrainEntry.getDrivingName());//协议驾校
            data.add(ownCarTrainEntry.getCfcarnumber());//车牌号
            data.add(ownCarTrainEntry.getCfchexing());//时长测试
            if("".equals(ownCarTrainEntry.getCfcartype())){
            data.add(" ");//车型
            }else{
            data.add(ownCarTrainEntry.getCfcartype());//车型

            }
            if("".equals(ownCarTrainEntry.getCfkemu())){
            data.add(" ");//科目
            }else{
            data.add(stateToString.subject(ownCarTrainEntry.getCfkemu()));//科目
            }
            data.add(ownCarTrainEntry.getCfprice());//单价
            data.add(ownCarTrainEntry.getCfamount());//金额
        }
        //头部数据
        String head[] = {
				"单据编号", "缴费日期", "协议驾校", "车牌号", "时长","车型","科目","单价", "金额"};
        //长度
        Integer length[] = {7000, 3000, 8000, 3000, 2600, 2600, 2600, 2600, 2600};

        List<Object> data2= listForSum(data,head,7,2,0);
        try {
            //导出Excel
            CommonExport.importExcelSum(response, "考前训练收费" + TimeFormat.getNowTime2() + ".xls", "考前训练收费", data, head, length,data2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	/**
	 *统计方法
	 * @param list1 完成遍历的集合
	 * @param head  表头
	 * @param num   求和的第一个字段的下标
	 * @param sum  需要增加多少个字段
	 * @return
	 */
	public List<Object> listForSum(List<Object> list1,String[] head,int num,int sum,int nextNum){

		Double money=0.0;

		List<Object>list=new ArrayList<>();
		DecimalFormat df = new DecimalFormat("#.00");
		list.add("合计：");
		for (int i = 0; i < num - 1; i++) {
			list.add(" ");
		}
		for(int i=0;i<sum;i++){

			for (int j = 0; j < list1.size() / head.length; j++) {
				if (list1.get(num + head.length*j)==null || "".equals(list1.get(num + head.length * j))) {
					money += 0.00;
				} else {
					money += Double.parseDouble(list1.get(num + head.length * j) + "");
				}
			}
			if(money==0.00||money==null){
				list.add("0.00");
			}else{
				if(".00".equals(df.format(money))){
					list.add("");
				}else{
					list.add(df.format(money));
				}
			}
			num++;
			money = 0.00;
		}
		if(nextNum!=0){
		 list.add("");
		  num+=nextNum;
		for (int j = 0; j < list1.size() / head.length; j++) {
			if (list1.get(num + head.length*j)==null || "".equals(list1.get(num + head.length * j))) {
				money += 0.00;
			} else {
				money += Double.parseDouble(list1.get(num + head.length * j) + "");
			}
		}
		if(money==0.00||money==null){
			list.add("0.00");
		}else{
			if(".00".equals(df.format(money))){
				list.add("");
			}else{
				list.add(df.format(money));
			}
		}
		}
		return list;
	}
}
